<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>班级管理 - 智慧教育考试系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind自定义主题 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            accent: '#FF9F43',
            neutral: '#F8FAFC',
            'neutral-dark': '#334155',
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .nav-hover {
        @apply transition-all duration-300 hover:bg-primary/10 hover:text-primary;
      }
      .btn-primary {
        @apply bg-primary text-white px-4 py-2 rounded-lg transition-all duration-300 hover:bg-primary/90 active:bg-primary/80;
      }
      .btn-secondary {
        @apply bg-white border border-gray-200 text-neutral-dark px-4 py-2 rounded-lg transition-all duration-300 hover:bg-gray-50 active:bg-gray-100;
      }
      .btn-danger {
        @apply bg-red-50 text-red-600 border border-red-200 px-3 py-1 rounded-lg transition-all duration-300 hover:bg-red-100 active:bg-red-200;
      }
      .btn-edit {
        @apply bg-blue-50 text-blue-600 border border-blue-200 px-3 py-1 rounded-lg transition-all duration-300 hover:bg-blue-100 active:bg-blue-200;
      }
      .modal-backdrop {
        @apply fixed inset-0 bg-black/50 z-50 flex items-center justify-center opacity-0 pointer-events-none transition-opacity duration-300;
      }
      .modal-backdrop.active {
        @apply opacity-100 pointer-events-auto;
      }
      .modal-content {
        @apply bg-white rounded-xl w-full max-w-md mx-4 transform translate-y-8 transition-transform duration-300;
      }
      .modal-backdrop.active .modal-content {
        @apply translate-y-0;
      }
    }
  </style>
</head>
<body class="font-inter bg-gray-50 text-neutral-dark min-h-screen flex flex-col">
  <!-- 顶部导航栏 -->
  <header class="bg-white border-b border-gray-200 sticky top-0 z-30">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <i class="fa fa-graduation-cap text-primary text-2xl"></i>
        <h1 class="text-xl font-bold text-primary">智慧教育考试系统</h1>
      </div>

      <div class="flex items-center space-x-6">
        <div class="hidden md:flex items-center space-x-4">
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-bell-o"></i>
          </button>
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-cog"></i>
          </button>
        </div>

        <div class="flex items-center space-x-2">
          <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa fa-user"></i>
          </div>
          <span class="hidden md:inline">张老师</span>
        </div>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-1 flex flex-col md:flex-row">
    <!-- 左侧导航 -->
    <aside class="w-full md:w-64 bg-white border-r border-gray-200 md:h-[calc(100vh-60px)] sticky md:sticky top-[60px] z-20">
      <!-- 角色切换 -->
      <div class="p-4 border-b border-gray-200">
        <h2 class="text-sm font-medium text-gray-500 mb-2">角色切换</h2>
        <div class="flex rounded-lg overflow-hidden border border-gray-200">
          <button id="teacher-tab" class="flex-1 py-2 px-3 bg-primary text-white text-sm font-medium">
            教师端
          </button>
          <button id="student-tab" class="flex-1 py-2 px-3 bg-white text-gray-600 text-sm font-medium hover:bg-gray-50">
            学生端
          </button>
        </div>
      </div>

      <!-- 教师导航菜单 -->
      <nav id="teacher-nav" class="p-2">
        <ul class="space-y-1">
          <li>
            <a href="/home" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-bar-chart w-5 text-center"></i>
              <span>教师控制台</span>
            </a>
          </li>
          <li>
            <a href="/Publish_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-pencil-square-o w-5 text-center"></i>
              <span>发布考试</span>
            </a>
          </li>
          <li>
            <a href="/History_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-history w-5 text-center"></i>
              <span>历史考试</span>
            </a>
          </li>
          <li>
            <a href="/Set_questions" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-magic w-5 text-center"></i>
              <span>一键出题</span>
            </a>
          </li>
          <li>
            <a href="/Question_Bank" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-book w-5 text-center"></i>
              <span>题库管理</span>
            </a>
          </li>
          <li>
            <a href="/stu_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-users w-5 text-center"></i>
              <span>学生管理</span>
            </a>
          </li>
          <li>
            <a href="/class_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover text-primary bg-primary/10">
              <i class="fa fa-th-large w-5 text-center"></i>
              <span>班级管理</span>
            </a>
          </li>
        </ul>
      </nav>

      <!-- 学生导航菜单 (默认隐藏) -->
      <nav id="student-nav" class="p-2 hidden">
        <ul class="space-y-1">
          <li>
            <a href="/Exam_record" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-file-text-o w-5 text-center"></i>
              <span>个人考试记录</span>
            </a>
          </li>
          <li>
            <a href="/Waiting_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-clock-o w-5 text-center"></i>
              <span>待考试</span>
              <span class="ml-auto bg-accent text-white text-xs px-2 py-0.5 rounded-full">3</span>
            </a>
          </li>
          <li>
            <a href="/Mistake_question" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-exclamation-circle w-5 text-center"></i>
              <span>错题本</span>
            </a>
          </li>
        </ul>
      </nav>
    </aside>

    <!-- 右侧内容区 -->
    <div class="flex-1 p-4 md:p-6 overflow-auto">
      <div class="mb-6">
        <div class="flex items-center">
          <a href="#" class="text-gray-500 hover:text-primary mr-2">
            <i class="fa fa-arrow-left"></i>
          </a>
          <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold">班级管理</h2>
        </div>
        <p class="text-gray-500 mt-1">管理班级基本信息，支持添加、修改和删除操作</p>
      </div>

      <!-- 搜索与添加区域 -->
      <div class="bg-white rounded-xl p-5 card-shadow mb-6">
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div class="relative w-full md:w-96">
            <input type="text" id="class-search"
                   placeholder="搜索班级名称、班主任..."
                   class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
            <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
          </div>

          <div class="flex items-center gap-3">
            <div class="hidden md:flex items-center space-x-2">
              <select id="option_select" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
                <option value="0">全部状态</option>
                <option value="1">正常</option>
                <option value="2">已毕业</option>
              </select>
            </div>

            <!-- 修改添加班级按钮，添加id用于绑定事件 -->
            <button id="addClassBtn" class="btn-primary flex items-center">
              <i class="fa fa-plus mr-2"></i> 添加班级
            </button>
          </div>
        </div>
      </div>

      <!-- 班级表格 -->
      <div class="bg-white rounded-xl card-shadow overflow-hidden">
        <div class="overflow-x-auto">
          <table class="w-full min-w-[800px]">
            <thead>
              <tr class="bg-gray-50 text-left">
                <th class="px-6 py-4 text-sm font-medium text-gray-600">
                  <div class="flex items-center">
                    <input type="checkbox" class="mr-2">
                    序号
                  </div>
                </th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">班级名称</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">年级</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">班主任</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">学生人数</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">成立日期</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">状态</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600 text-right">操作</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-100" id="classes">
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </main>

  <!-- 编辑班级弹窗 -->
  <div id="editModal" class="modal-backdrop">
    <div class="modal-content p-6">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-bold">编辑班级</h3>
        <button id="closeModal" class="text-gray-500 hover:text-gray-700">
          <i class="fa fa-times"></i>
        </button>
      </div>

      <form id="editForm">
        <input type="hidden" id="editClassId" readonly>
        <div class="mb-4">
          <label for="className" class="block text-sm font-medium text-gray-700 mb-1">班级名称</label>
          <input type="text" id="className" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" required>
        </div>

        <div class="mb-4">
          <label for="grade" class="block text-sm font-medium text-gray-700 mb-1">年级</label>
          <input type="text" id="grade" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" required>
        </div>

        <div class="mb-4">
          <label for="teacherName" class="block text-sm font-medium text-gray-700 mb-1">班主任</label>
          <input type="text" id="teacherName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" required>
        </div>

        <div class="mb-6">
          <label for="status" class="block text-sm font-medium text-gray-700 mb-1">状态</label>
          <input type="text" id="status" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" required>
        </div>

        <div class="flex justify-end space-x-3">
          <button type="button" id="cancelEdit" class="btn-secondary">取消</button>
          <button type="submit" class="btn-primary">确认修改</button>
        </div>
      </form>
    </div>
  </div>

  <!-- 添加班级弹窗 (新增内容) -->
  <div id="addClassModal" class="modal-backdrop">
    <div class="modal-content p-6">
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-bold">添加班级</h3>
        <button id="closeAddModalBtn" class="text-gray-500 hover:text-gray-700">
          <i class="fa fa-times"></i>
        </button>
      </div>

      <form id="addClassForm">
        <div class="mb-4">
          <label for="newClassName" class="block text-sm font-medium text-gray-700 mb-1">班级名称 <span class="text-red-500">*</span></label>
          <input type="text" id="newClassName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" required>
        </div>

        <div class="mb-4">
          <label for="newGrade" class="block text-sm font-medium text-gray-700 mb-1">年级 <span class="text-red-500">*</span></label>
          <input type="text" id="newGrade" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" required>
        </div>

        <div class="mb-4">
          <label for="newTeacherName" class="block text-sm font-medium text-gray-700 mb-1">班主任 <span class="text-red-500">*</span></label>
          <input type="text" id="newTeacherName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" required>
        </div>

        <div class="mb-4">
          <label for="newCreateDate" class="block text-sm font-medium text-gray-700 mb-1">创建时间 <span class="text-red-500">*</span></label>
          <input type="date" id="newCreateDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" required>
        </div>

        <div class="mb-6">
          <label for="newStatus" class="block text-sm font-medium text-gray-700 mb-1">状态 <span class="text-red-500">*</span></label>
          <select id="newStatus" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors" required>
            <option value="正常">正常</option>
            <option value="已毕业">已毕业</option>
          </select>
        </div>

        <div class="flex justify-end space-x-3">
          <button type="button" id="cancelAddBtn" class="btn-secondary">取消</button>
          <button type="submit" class="btn-primary">确认添加</button>
        </div>
      </form>
    </div>
  </div>

  <script>
    // 角色切换功能
    document.getElementById('teacher-tab').addEventListener('click', function() {
      this.classList.add('bg-primary', 'text-white');
      this.classList.remove('bg-white', 'text-gray-600');
      document.getElementById('student-tab').classList.add('bg-white', 'text-gray-600');
      document.getElementById('student-tab').classList.remove('bg-primary', 'text-white');
      document.getElementById('teacher-nav').classList.remove('hidden');
      document.getElementById('student-nav').classList.add('hidden');
    });


    // 获取表格元素
    const class_table = document.getElementById('classes')

    // 读取class表所有内容
    const class_all = async () => {
      const response = await fetch('/class_all',{
        method:'GET',
        headers:{
          'Content-Type': 'application/json'
        }
      })
      const result = await response.json();
      if (result.success){
        class_table.innerHTML = classHTML(result.data)
      }
      else {
        alert('出现错误'+result.error)
      }
    }

    // 时间格式化函数
    const formatDate = (dateString) => {
      if (!dateString) return '-';

      try {
          const date = new Date(dateString);
          return date.toLocaleDateString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit'
          });
      } catch (error) {
          console.error('日期格式化错误:', error);
          return dateString;
      }
    };

    // 将数据渲染到前端
    function classHTML(data){
      let HTML = '';
      data.forEach((cls) => {
        HTML += `<tr class="hover:bg-gray-50 transition-colors">
                  <td class="px-6 py-4 text-sm text-gray-700">
                    <div class="flex items-center">
                      <input type="checkbox" class="mr-2">
                      ${ cls.id }
                    </div>
                  </td>
                  <td class="px-6 py-4 text-sm text-gray-700">${ cls.class_name }</td>
                  <td class="px-6 py-4 text-sm text-gray-700">${ cls.grade }</td>
                  <td class="px-6 py-4 text-sm text-gray-700">${ cls.teacher_name }</td>
                  <td class="px-6 py-4 text-sm text-gray-700">${ cls.stu_num }</td>
                  <td class="px-6 py-4 text-sm text-gray-700">${ formatDate(cls.create_date) }</td>
                  <td class="px-6 py-4 text-sm">
                    <span class="bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full">${ cls.status }</span>
                  </td>
                  <td class="px-6 py-4 text-sm text-right">
                    <div class="flex justify-end space-x-2">
                      <button class="btn-edit text-sm" onclick="openEditModal(${cls.id},'${cls.class_name}','${cls.teacher_name}','${cls.status}','${cls.grade}')">
                        <i class="fa fa-pencil mr-1"></i> 编辑
                      </button>
                      <button class="btn-danger text-sm" onclick="deleteClass(${cls.id}, event)">
                        <i class="fa fa-trash mr-1"></i> 删除
                      </button>
                    </div>
                  </td>
                </tr>`;
      });
      return HTML;
    }

    // 搜索功能
    const searchInput = document.getElementById('class-search');

    async function searchClass(keyword) {
      searchInput.disabled = true;
      searchInput.placeholder = "搜索中...";

      try {
        const response = await fetch('/class_select', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ keyword: keyword.trim() })
        });
        const result = await response.json();

        if (result.success) {
          if (!result.data || (Array.isArray(result.data) && result.data.length === 0)) {
            class_table.innerHTML = '';
          } else {
            class_table.innerHTML = classHTML(result.data);
          }
        } else {
          alert('出现错误' + result.error);
        }
      } catch (error) {
        console.error('搜索失败:', error);
        alert('搜索失败，请重试');
      } finally {
        searchInput.disabled = false;
        searchInput.placeholder = "搜索班级名称、班主任...";
      }
    }

    searchInput.addEventListener('keydown', function(e) {
      if (e.keyCode === 13 || e.key === 'Enter') {
        e.preventDefault();
        const keyword = this.value;
        if (keyword.trim()) {
          searchClass(keyword);
        } else {
          alert('请输入搜索内容');
        }
      }
    });

    // 下拉框筛选
    const change_option = () => {
      const option_select = document.getElementById('option_select');

      option_select.addEventListener('change', async (e) => {
        const selectedStatus = e.target.value;
        try {
          const response = await fetch('/class_option', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({ selectedStatus: selectedStatus })
          });
          const result = await response.json();

          if (result.success) {
            if (!result.data || (Array.isArray(result.data) && result.data.length === 0)) {
              class_table.innerHTML = '';
            } else {
              class_table.innerHTML = classHTML(result.data);
            }
          } else {
            alert('出现错误' + result.error);
          }
        } catch (error) {
          console.error('筛选失败:', error);
          alert('筛选失败，请重试');
        }
      });
    };

    // 删除班级函数
    const deleteClass = async (classId, event) => {
      const originalText = event.target.innerHTML;

      if (!confirm('确定要删除这个班级吗？此操作不可撤销！')) {
        return;
      }

      try {
        event.target.innerHTML = '<i class="fa fa-spinner fa-spin mr-1"></i> 删除中...';
        event.target.disabled = true;

        const response = await fetch(`/deleteClass/${classId}`, {
          method: 'DELETE',
          headers: {
            'Content-Type': 'application/json',
          }
        });

        const result = await response.json();

        if (result.success) {
          showMessage('班级删除成功', 'success');
          class_all();
        } else {
          throw new Error(result.error || '删除失败');
        }

      } catch (error) {
        console.error('删除班级失败:', error);
        showMessage('删除失败: ' + error.message, 'error');
      } finally {
        event.target.innerHTML = originalText;
        event.target.disabled = false;
      }
    };

    // 编辑弹窗相关功能
    const editModal = document.getElementById('editModal');
    const closeModal = document.getElementById('closeModal');
    const cancelEdit = document.getElementById('cancelEdit');
    const editForm = document.getElementById('editForm');

    // 打开编辑弹窗并填充数据
    function openEditModal(id,class_name,teacher_name,status,grade) {
      document.getElementById('editClassId').value = id
      document.getElementById('className').value = class_name;
      document.getElementById('grade').value = grade;
      document.getElementById('teacherName').value = teacher_name;
      document.getElementById('status').value = status;

      editModal.classList.add('active');
      document.body.style.overflow = 'hidden'; // 防止背景滚动
    }

    // 关闭编辑弹窗
    function closeEditModal() {
      editModal.classList.remove('active');
      document.body.style.overflow = ''; // 恢复背景滚动
    }

    // 提交编辑表单
    editForm.addEventListener('submit', async function(e) {
      e.preventDefault();

      const classId = document.getElementById('editClassId').value;
      const updatedData = {
        class_name: document.getElementById('className').value,
        grade: document.getElementById('grade').value,
        teacher_name: document.getElementById('teacherName').value,
        status: document.getElementById('status').value
      };
      try {
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;

        submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 保存中...';
        submitBtn.disabled = true;

        const response = await fetch(`/updateClass/${classId}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(updatedData)
        });

        const result = await response.json();

        if (result.success) {
          showMessage('班级更新成功', 'success');
          closeEditModal();
          class_all(); // 重新加载数据
        } else {
          throw new Error(result.error || '更新失败');
        }

      } catch (error) {
        console.error('更新班级失败:', error);
        showMessage('更新失败: ' + error.message, 'error');
      } finally {
        const submitBtn = this.querySelector('button[type="submit"]');
        submitBtn.innerHTML = '确认修改';
        submitBtn.disabled = false;
      }
    });

    // 绑定弹窗关闭事件
    closeModal.addEventListener('click', closeEditModal);
    cancelEdit.addEventListener('click', closeEditModal);

    // 点击弹窗外部关闭
    editModal.addEventListener('click', function(e) {
      if (e.target === this) {
        closeEditModal();
      }
    });

    // 添加班级弹窗相关功能
    const addClassModal = document.getElementById('addClassModal');
    const addClassBtn = document.getElementById('addClassBtn');
    const closeAddModalBtn = document.getElementById('closeAddModalBtn'); // 修改变量名
    const cancelAddBtn = document.getElementById('cancelAddBtn'); // 修改变量名
    const addClassForm = document.getElementById('addClassForm');

    // 打开添加班级弹窗
    function openAddModal() {
      addClassModal.classList.add('active');
      document.body.style.overflow = 'hidden'; // 防止背景滚动
    }

    // 关闭添加班级弹窗（修改函数名）
    function closeAddClassModal() {
      addClassModal.classList.remove('active');
      document.body.style.overflow = ''; // 恢复背景滚动
    }

    // 提交添加班级表单
    addClassForm.addEventListener('submit', async function(e) {
      e.preventDefault();

      const newClassData = {
        class_name: document.getElementById('newClassName').value,
        grade: document.getElementById('newGrade').value,
        teacher_name: document.getElementById('newTeacherName').value,
        create_date: document.getElementById('newCreateDate').value,
        status: document.getElementById('newStatus').value,
        stu_num: 0 // 新班级初始学生数为0
      };

      try {
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;

        submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 添加中...';
        submitBtn.disabled = true;

        const response = await fetch('/addClass', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(newClassData)
        });

        const result = await response.json();

        if (result.success) {
          showMessage('班级添加成功', 'success');
          closeAddClassModal(); // 调用修改后的函数
          class_all(); // 重新加载数据
          addClassForm.reset(); // 重置表单
          // 重置默认日期
          const today = new Date().toISOString().split('T')[0];
          document.getElementById('newCreateDate').value = today;
        } else {
          throw new Error(result.error || '添加失败');
        }

      } catch (error) {
        console.error('添加班级失败:', error);
        showMessage('添加失败: ' + error.message, 'error');
      } finally {
        const submitBtn = this.querySelector('button[type="submit"]');
        submitBtn.innerHTML = '确认添加';
        submitBtn.disabled = false;
      }
    });

    // 绑定添加弹窗事件（使用修改后的变量名和函数名）
    addClassBtn.addEventListener('click', openAddModal);
    closeAddModalBtn.addEventListener('click', closeAddClassModal);
    cancelAddBtn.addEventListener('click', closeAddClassModal);

    // 点击添加弹窗外部关闭
    addClassModal.addEventListener('click', function(e) {
      if (e.target === this) {
        closeAddClassModal(); // 调用修改后的函数
      }
    });



    // 消息提示功能
    const showMessage = (message, type = 'info') => {
      const messageDiv = document.createElement('div');
      const bgColor = type === 'success' ? 'bg-green-100 border-green-400 text-green-700' :
                     type === 'error' ? 'bg-red-100 border-red-400 text-red-700' :
                     'bg-blue-100 border-blue-400 text-blue-700';

      messageDiv.className = `${bgColor} border px-4 py-3 rounded fixed top-4 right-4 z-50 transition-all duration-300`;
      messageDiv.innerHTML = `
          <div class="flex items-center">
              <i class="fa ${type === 'success' ? 'fa-check' : type === 'error' ? 'fa-exclamation-triangle' : 'fa-info'} mr-2"></i>
              <span>${message}</span>
              <button class="ml-4 text-gray-500 hover:text-gray-700" onclick="this.parentElement.parentElement.remove()">
                  <i class="fa fa-times"></i>
              </button>
          </div>
      `;
      document.body.appendChild(messageDiv);

      // 3秒后自动消失
      setTimeout(() => {
        if (messageDiv.parentNode) {
          messageDiv.remove();
        }
      }, 3000);
    };

    // 初始化页面后执行
    document.addEventListener('DOMContentLoaded',()=>{
      class_all(); // 渲染所有数据
      change_option();
    });
  </script>
</body>
</html>